//
//  TaskGuiJiVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2021/4/7.
//  Copyright © 2021 吕晶. All rights reserved.
//

#import "TaskGuiJiVC.h"
#import "TaskGuiJiModel.h"
#import "TaskGuiJiAnnotation.h"
#import "TaskGuiJiAnnotationView.h"
#import "TaskGuiJiStatusCell.h"
#import "TaskGuiJiStatusHeadView.h"

@interface TaskGuiJiVC () <MAMapViewDelegate,AMapSearchDelegate,UITableViewDelegate,UITableViewDataSource> {
    CGFloat tableViewTopMin;
    CGFloat tableViewTopMid;
    CGFloat tableViewTopMax;
    NSInteger currentOrderIndex;//当前显示的订单下标
    BOOL isTableViewScroll;//判断tableview是否可以改变frame
    int page;
}

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) MAPolyline *polyline;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) TaskGuiJiModel *currentModel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) TaskGuiJiStatusHeadView *headView;
@property (nonatomic, strong) NSArray <TaskGuiJiOrderStatusModel *>*statusArray;
@property (nonatomic, strong) UILabel *waitStatusLab;

@end

@implementation TaskGuiJiVC

-(UILabel *)waitStatusLab {
    if (!_waitStatusLab) {
        _waitStatusLab = [[UILabel alloc] initWithFrame:CGRectMake((ScreenW - 200) * 0.5, StatusBarHeight + 10, 200, 20)];
        _waitStatusLab.text = @"获取司机实时位置中...";
        _waitStatusLab.textAlignment = NSTextAlignmentCenter;
        _waitStatusLab.textColor = HexColor(0x3D68EB);
        _waitStatusLab.backgroundColor = HexColorA(0x3D68EB, 0.1);
        _waitStatusLab.font = [UIFont systemFontOfSize:15];
        _waitStatusLab.layer.masksToBounds = YES;
        _waitStatusLab.layer.cornerRadius = 10;
    }
    return _waitStatusLab;
}

-(TaskGuiJiStatusHeadView *)headView {
    if (!_headView) {
        _headView = [[TaskGuiJiStatusHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 30 + 15 + 220 + 10)];
        __weak_self;
        _headView.scrollBlock = ^(NSInteger idx) {
            __strong_self;
            if (idx != strongSelf->currentOrderIndex) {
                strongSelf->currentOrderIndex = idx;
                [strongSelf refreshMapView];
            }
        };
        _headView.shiShiLocationBlock = ^{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否获取司机实时位置？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakself requestForDriverLocation];
            }];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

            }];
            [alert addAction:sureAction];
            [alert addAction:cancleAction];
            [weakself presentViewController:alert animated:YES completion:nil];
        };
        _headView.sheBeiLocationBlock = ^{
            [weakself sheBeiClick];
        };
    }
    return _headView;
}

//设备定位点击
- (void)sheBeiClick {
    TaskGuiJiOrderModel *model = self.currentModel.list[currentOrderIndex];
    if (model.equipment_id && model.equipment_starttime) {
        page = 0;
        [self requestForSheBeiWithID:model.equipment_id withStartTime:model.equipment_starttime withEndTime:@"" withPreviousArrayLastPoint:nil];
    }
}

//请求获取设备定位
- (void)requestForSheBeiWithID:(int)equipment_id withStartTime:(NSString *)equipment_starttime withEndTime:(NSString *)equipment_endtime withPreviousArrayLastPoint:(TaskGuiJiOrderSheBeiPointModel *)lastPoint {
    page ++;
    [HttpRequest PostWithApi:LogisticsSupplierTaskGetSheBeiLocation params:@{@"e_id":@(equipment_id),@"starttime":equipment_starttime,@"endtime":equipment_endtime,@"page":@(page)} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            NSArray *arr = [TaskGuiJiOrderSheBeiPointModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            if (lastPoint) {
                NSMutableArray *mut = [NSMutableArray arrayWithArray:arr];
                [mut insertObject:lastPoint atIndex:0];
                arr = mut;
            }
            BOOL has_next = [responseObject[@"has_next"] boolValue];
            if (arr.count) {
                if (equipment_endtime.length) {
                    [self drawSheBeiLineWithArray:arr isFirst:NO];
                }else {
                    [self drawSheBeiLineWithArray:arr isFirst:YES];
                }
            }
            if (has_next) {
                [self requestForSheBeiWithID:equipment_id withStartTime:equipment_starttime withEndTime:((TaskGuiJiOrderSheBeiPointModel *)arr.lastObject).createtime withPreviousArrayLastPoint:arr.lastObject];
            }
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

//绘制设备线路
- (void)drawSheBeiLineWithArray:(NSArray *)array isFirst:(BOOL)isFirst {
    if (isFirst) {
        [self cleanMapView];
    }
    CLLocationCoordinate2D arr[array.count];
    for (int i = 0; i < array.count; i ++) {
        TaskGuiJiOrderSheBeiPointModel *model = (TaskGuiJiOrderSheBeiPointModel *)array[i];
//        arr[i] = CLLocationCoordinate2DMake([model.lat doubleValue], [model.lng doubleValue]);
        arr[i] = AMapCoordinateConvert(CLLocationCoordinate2DMake([model.lat doubleValue],[model.lng doubleValue]), AMapCoordinateTypeGPS);
        //绘画起点、终点、途经点
        if (model.type == 1) {
            TaskGuiJiAnnotation *qiAn = [TaskGuiJiAnnotation new];
            qiAn.type = 1;
//            qiAn.coordinate = CLLocationCoordinate2DMake([model.lat doubleValue], [model.lng doubleValue]);
            qiAn.coordinate = arr[i];
            [self.mapView addAnnotation:qiAn];
        }
        if (model.type == 2) {
            TaskGuiJiAnnotation *zhongAn = [TaskGuiJiAnnotation new];
            zhongAn.type = 3;
//            zhongAn.coordinate = CLLocationCoordinate2DMake([model.lat doubleValue], [model.lng doubleValue]);
            zhongAn.coordinate = arr[i];
            [self.mapView addAnnotation:zhongAn];
        }
    }
    MAPolyline *line = [MAPolyline polylineWithCoordinates:arr count:array.count];
    [self.mapView addOverlay:line];
    if (isFirst) {
        //第一次请求，绘制路径时跳转到路径显示区域，其余的不跳转
        [self.mapView showOverlays:@[line] animated:YES];
    }
}

//清空地图
- (void)cleanMapView {
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.mapView removeAnnotations:self.mapView.annotations];
}

-(NSArray<TaskGuiJiOrderStatusModel *> *)statusArray {
    if (!_statusArray) {
        _statusArray = [NSArray array];
    }
    return _statusArray;
}

-(TaskGuiJiModel *)currentModel {
    if (!_currentModel) {
        _currentModel = [TaskGuiJiModel new];
    }
    return _currentModel;
}

-(UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, StatusBarHeight + 7, 44, 44)];
        [_backBtn setImage:[UIImage imageNamed:@"icon_map_back"] forState:0];
        [_backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

- (void)backClick {
    [self.rt_navigationController popViewControllerAnimated:YES];
}

- (AMapSearchAPI *)search {
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}

- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
        _mapView.delegate = self;
        _mapView.allowsBackgroundLocationUpdates = YES;//iOS9以上系统必须配置
    }
    return _mapView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, tableViewTopMax, ScreenW - 30, ScreenH - tableViewTopMin - BottomHeight)];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
        _tableView.tableHeaderView = self.headView;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    isTableViewScroll = YES;
    tableViewTopMin = 150;
    tableViewTopMax = ScreenH - 150;
    tableViewTopMid = (tableViewTopMax - tableViewTopMin) * 0.5 + tableViewTopMin;
    [AMapServices sharedServices].apiKey = @"9f54e2b9c863a0119364c5eb222c1070";
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.backBtn];
    [self requestForData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestForData) name:ReceiptDeliveryRefreshTaskDriverGuiJi object:nil];
}

- (void)requestForDriverLocation {
    [HttpRequest PostWithApi:LogisticsSupplierTaskGetDriverLocation params:@{@"sta_id":self.currentModel.Id} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [self.view addSubview:self.waitStatusLab];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (self.tableView.nim_top >= tableViewTopMid) {
        __weak_self;
        [UIView animateWithDuration:0.5 animations:^{
            __strong_self;
            weakself.tableView.nim_top = strongSelf->tableViewTopMax;
        } completion:nil];
    }else {
        __weak_self;
        [UIView animateWithDuration:0.5 animations:^{
            __strong_self;
            weakself.tableView.nim_top = strongSelf->tableViewTopMin;
        } completion:nil];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        CGFloat offSetY = scrollView.contentOffset.y;
        if (self.tableView.nim_top <= tableViewTopMin) {
            if (offSetY > 0) {
                NSLog(@"到顶，继续上滑");
                self.tableView.nim_top = tableViewTopMin;
                isTableViewScroll = NO;
            }else {
                NSLog(@"到顶，下滑");
                isTableViewScroll = YES;
            }
        }else if (self.tableView.nim_top >= tableViewTopMax) {
            if (offSetY < 0) {
                NSLog(@"到底，继续下滑");
                self.tableView.nim_top = tableViewTopMax;
                isTableViewScroll = NO;
            }else {
                NSLog(@"到底，上滑");
                isTableViewScroll = YES;
            }
        }
        NSLog(@"***%f***",offSetY);
        if (isTableViewScroll) {
            self.tableView.nim_top -= offSetY;
            [self.tableView setContentOffset:CGPointMake(0, 0) animated:NO];
        }
    }
}

- (void)drawMapViewWithStartPoint:(MAPointAnnotation *)start_point WithEndPoint:(MAPointAnnotation *)end_point withCenterPoint:(MAPointAnnotation *)center_point {
    //设置地图显示区域
    NSMutableArray *quYuArray = [NSMutableArray array];
    if (start_point.coordinate.latitude) {
        [quYuArray addObject:start_point];
    }
    if (end_point.coordinate.latitude) {
        [quYuArray addObject:end_point];
    }
    if (center_point.coordinate.latitude) {
        [quYuArray addObject:center_point];
    }
    [self.mapView showAnnotations:quYuArray edgePadding:UIEdgeInsetsMake(10, 10, 10, 10) animated:YES];
    
    //设置地图路线规划
    AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
    navi.requireExtension = YES;//是否返回扩展信息，默认为 NO
    navi.strategy = 5;// 驾车导航策略([default = 0]) 0-速度优先（时间）；1-费用优先（不走收费路段的最快道路）；2-距离优先；3-不走快速路；4-结合实时交通（躲避拥堵）；5-多策略（同时使用速度优先、费用优先、距离优先三个策略）；6-不走高速；7-不走高速且避免收费；8-躲避收费和拥堵；9-不走高速且躲避收费和拥堵
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:start_point.coordinate.latitude
                                               longitude:start_point.coordinate.longitude];
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:end_point.coordinate.latitude
                                               longitude:end_point.coordinate.longitude];
    /* 途径点. */
    if (center_point.coordinate.latitude) {
        AMapGeoPoint *pp = [AMapGeoPoint locationWithLatitude:center_point.coordinate.latitude longitude:center_point.coordinate.longitude];
        navi.waypoints = @[pp];
    }
    [self.search AMapDrivingRouteSearch:navi];//驾车路线规划
    
    //绘画起点、终点、途经点
    TaskGuiJiAnnotation *qiAn = [TaskGuiJiAnnotation new];
    qiAn.type = 1;
    qiAn.coordinate = CLLocationCoordinate2DMake(start_point.coordinate.latitude, start_point.coordinate.longitude);
    [self.mapView addAnnotation:qiAn];
    
    TaskGuiJiAnnotation *zhongAn = [TaskGuiJiAnnotation new];
    zhongAn.type = 2;
    zhongAn.coordinate = CLLocationCoordinate2DMake(end_point.coordinate.latitude, end_point.coordinate.longitude);
    [self.mapView addAnnotation:zhongAn];
    
    if (center_point.coordinate.latitude) {
        TaskGuiJiAnnotation *tuAn = [TaskGuiJiAnnotation new];
        tuAn.type = 3;
        tuAn.coordinate = CLLocationCoordinate2DMake(center_point.coordinate.latitude, center_point.coordinate.longitude);
        [self.mapView addAnnotation:tuAn];
    }
}

- (void)refreshMapView {
    if (self.currentModel.list.count) {
        self.statusArray = self.currentModel.list[currentOrderIndex].time_status;
        self.statusArray.firstObject.isFirst = YES;
        self.statusArray.lastObject.isLast = YES;
        self.headView.model = self.currentModel;
        [self.tableView reloadData];
        
        [self cleanMapView];
        
        TaskGuiJiOrderModel *model = self.currentModel.list[currentOrderIndex];

        MAPointAnnotation *start_point = [MAPointAnnotation new];
        start_point.coordinate = CLLocationCoordinate2DMake([model.s_lat doubleValue], [model.s_lng doubleValue]);
        
        MAPointAnnotation *end_point = [MAPointAnnotation new];
        end_point.coordinate = CLLocationCoordinate2DMake([model.r_lat doubleValue], [model.r_lng doubleValue]);
        
        MAPointAnnotation *driver_point = [MAPointAnnotation new];
        driver_point.coordinate = CLLocationCoordinate2DMake([model.driver_lat doubleValue], [model.driver_lng doubleValue]);
        
        [self drawMapViewWithStartPoint:start_point WithEndPoint:end_point withCenterPoint:driver_point];
    }
}

- (void)requestForData {
    currentOrderIndex = 0;
    [HttpRequest PostWithApi:LogisticsSupplierTaskGuiJi params:@{@"sta_id":self.sta_id} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.currentModel = [TaskGuiJiModel mj_objectWithKeyValues:responseObject];
            [self refreshMapView];
            [self.waitStatusLab removeFromSuperview];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", error);
}

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    if (response.route == nil){
        return;
    }
    if (response.count > 0){
        //直接取第一个方案
        AMapPath *path = response.route.paths[0];
        //移除旧折线对象
        [_mapView removeOverlay:_polyline];
        //构造折线对象
        _polyline = [self polylinesForPath:path];
        //添加新的遮盖，然后会触发代理方法(- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay)进行绘制
        [_mapView addOverlay:_polyline];
    }
}

//路线解析
- (MAPolyline *)polylinesForPath:(AMapPath *)path{
    if (path == nil || path.steps.count == 0){
        return nil;
    }
    NSMutableString *polylineMutableString = [@"" mutableCopy];
    for (AMapStep *step in path.steps) {
        [polylineMutableString appendFormat:@"%@;",step.polyline];
    }
    NSUInteger count = 0;
    CLLocationCoordinate2D *coordinates = [self coordinatesForString:polylineMutableString
                                                     coordinateCount:&count
                                                          parseToken:@";"];
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
    
    free(coordinates), coordinates = NULL;
    return polyline;
}

//解析经纬度
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount
                                      parseToken:(NSString *)token{
    if (string == nil){
        return NULL;
    }
    
    if (token == nil){
        token = @",";
    }
    
    NSString *str = @"";
    if (![token isEqualToString:@","]){
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }else{
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL){
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++){
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    return coordinates;
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]]){
        MAPolyline *polyline = (MAPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:polyline];
        
        //添加纹理图片
        //若设置了纹理图片，设置线颜色、连接类型和端点类型将无效。
//        polylineRenderer.strokeImage  = [UIImage imageNamed:@"wenli"];
        polylineRenderer.lineWidth    = 5.f;
        
        polylineRenderer.strokeColor  = HexColor(0x6DD26D);
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.lineCapType  = kMALineCapRound;
        polylineRenderer.miterLimit   = 1.f;
        
        return polylineRenderer;
    }
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    // 自定义大头针
    if ([annotation isKindOfClass:[TaskGuiJiAnnotation class]]) {
        static NSString *pinID = @"TaskGuiJiAnnotationView";
        TaskGuiJiAnnotationView *customPinView = (TaskGuiJiAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
        if (!customPinView) {
           customPinView = [[TaskGuiJiAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
        }
        customPinView.annotation = (TaskGuiJiAnnotation *)annotation;
        return customPinView;
    }
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.statusArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TaskGuiJiStatusCell *cell = [TaskGuiJiStatusCell TaskGuiJiStatusCellWithTableView:tableView];
    cell.model = self.statusArray[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TaskGuiJiStatusCell *cell = [TaskGuiJiStatusCell TaskGuiJiStatusCellWithTableView:tableView];
    cell.model = self.statusArray[indexPath.row];
    return cell.height;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
